//
//  iFlowerAppDelegate.m
//  iFlower
//
//  Created by Hoang Thuc on 14/07/2010.
//  Copyright iNIL 2010. All rights reserved.
//

#import "iFlowerAppDelegate.h"
#import "RootViewController.h"
#import "User.h"
#import "Basket.h"
#import "Payment.h"
#import "PayPal.h"
#import "PayPalContext.h"
#import "Order.h"
#import "DeliveryOptions.h"
#import "Reachability.h"
NSString* const kRegisterURL = @"http://flowersonline24.com/register.php";
@interface iFlowerAppDelegate()
@property (nonatomic, retain) Reachability* reachability;
@end

@implementation iFlowerAppDelegate

@synthesize window;
@synthesize navigationController;
@synthesize logined;
@synthesize downloadQueue;
@synthesize user;
@synthesize basket;
@synthesize payment;
@synthesize order;
@synthesize newAccount;
@synthesize deliveryOptions;
@synthesize reachability;
- (void) handleNetworkChange:(NSNotification *)notice
{
	NetworkStatus remoteHostStatus = [self.reachability currentReachabilityStatus];
	
	if(remoteHostStatus == NotReachable) {
		NSLog(@"no");
		NSString *msg = @"Appserver is not reachable! This requires Internet connectivity.";
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Network Problem" 
                                                        message:msg 
                                                       delegate:nil 
                                              cancelButtonTitle:@"OK" 
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];		
	}
	else if (remoteHostStatus == ReachableViaWiFi) {
		NSLog(@"wifi");
		[self.downloadQueue setMaxConcurrentOperationCount:4];
	}
	else if (remoteHostStatus == ReachableViaWWAN) {
		NSLog(@"cell");
		[self.downloadQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];
	}
}

#pragma mark -
#pragma mark share delegate

+ (iFlowerAppDelegate*) shareDelegate
{
	return (iFlowerAppDelegate*) [[UIApplication sharedApplication] delegate];
}
- (void)openSafariToRegister
{
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:kRegisterURL]];
}
#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    // Override point for customization after app launch    
	self.downloadQueue = [[NSOperationQueue alloc] init];
	self.logined = NO;
	self.basket = [Basket new];
	self.payment = [Payment new];
	self.order = [Order new];
	self.order.basket = self.basket;
	self.deliveryOptions = [DeliveryOptions new];
	self.deliveryOptions.flowers_for = @"E";
	self.deliveryOptions.deliver_to = @"E";
	self.deliveryOptions.is_funeral = @"N";
	self.deliveryOptions.funeralMin = @"";
	self.deliveryOptions.funeralHour = @"";
	self.deliveryOptions.deceased_name = @"";
	self.deliveryOptions.terms = @"Y";
	self.order.deliveryOptions = self.deliveryOptions;
	[window addSubview:[navigationController view]];
    [window makeKeyAndVisible];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNetworkChange:) name:kReachabilityChangedNotification object:nil];
	
	self.reachability = [Reachability reachabilityForInternetConnection];
	[self.reachability startNotifier];
	//Initialize the PayPal Library in a separate thread so the application is not blocked
	[NSThread detachNewThreadSelector:@selector(initializePayPalMEP) toTarget:self withObject:nil];
	return YES;
}


- (void)applicationWillTerminate:(UIApplication *)application {
	// Save data if appropriate
}
- (void)applicationWillResignActive:(UIApplication *)application {
	NSLog(@"applicationWillResignActive");
	/*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
	[[NSNotificationCenter defaultCenter] postNotificationName: @"applicationWillResignActive" object: nil];
}



#pragma mark -
#pragma mark Memory management

- (void)dealloc {
	[self.order release];
	[self.deliveryOptions release];
	[self.newAccount release];
	[payment release];
	[basket release];
	[user release];
	[downloadQueue release];
	[navigationController release];
	[window release];
	[super dealloc];
}
- (void) refreshBasket
{
	[self.basket release];
	self.basket = [Basket new];
	[self.deliveryOptions release];
	[self.order release];
	self.order = [Order new];
	self.deliveryOptions = [DeliveryOptions new];
	self.deliveryOptions.flowers_for = @"E";
	self.deliveryOptions.deliver_to = @"E";
	self.deliveryOptions.is_funeral = @"N";
	self.deliveryOptions.funeralMin = @"";
	self.deliveryOptions.funeralHour = @"";
	self.deliveryOptions.deceased_name = @"";
	self.deliveryOptions.terms = @"Y";
	self.order.deliveryOptions = self.deliveryOptions;
	self.order.basket = self.basket;
}
#pragma mark -
#pragma mark Public methods
-(void)initializePayPalMEP {
	//Initialize the PayPal Library on the Sandbox server
	//[PayPal initializeWithAppID:@"APP-80W284485P519543T" forEnvironment:ENV_SANDBOX];
	[PayPal initializeWithAppID:@"APP-1SP54378P4720060L" forEnvironment:ENV_LIVE];
}

- (void)showLoadingView
{
    if (loadingView == nil)
    {
        loadingView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 480.0)];
        loadingView.opaque = NO;
        loadingView.backgroundColor = [UIColor darkGrayColor];
        loadingView.alpha = 0.5;
		
        UIActivityIndicatorView *spinningWheel = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(142.0, 222.0, 37.0, 37.0)];
        [spinningWheel startAnimating];
        spinningWheel.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
        [loadingView addSubview:spinningWheel];
        [spinningWheel release];
    }
    
    [window addSubview:loadingView];
}

- (void)hideLoadingView
{
    [loadingView removeFromSuperview];
}
@end

